package io.scnb.lesson002.demo5;

import io.scnb.lesson002.demo1.Car;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

public class InstantiationAwareBeanPostProcessorTest {
    /**
     * 定义bean的时候，设置名称为奥迪，但是最终从容器中得到的实例中的名称确实保时捷
     * 定义和输出不一致的原因是在InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法中
     * 手动创建了一个实例直接返回了，而不是依靠spring内部去创建这个实例
     */
    @Test
    public void test1() {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        
        // 添加一个BeanPostProcessor -> InstantiationAwareBeanPostProcessor
        factory.addBeanPostProcessor(new InstantiationAwareBeanPostProcessor() {
            @Override
            public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
                System.out.println("调用postProcessBeforeInstantiation");
                if (beanClass == Car.class) {
                    Car car = new Car();
                    car.setName("保时捷");
                    return car;
                }
                return null;
            }
        });
        
        // 定义一个car bean
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Car.class).addPropertyValue("name", "奥迪").getBeanDefinition();
        
        factory.registerBeanDefinition("car", beanDefinition);
        
        // 从容器中获取car这个bean的实例
        System.out.println(factory.getBean("car"));

    }
}
